package com.hand.wfive.fragment.file

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import butterknife.OnClick
import com.alibaba.android.arouter.launcher.ARouter
import com.doris.media.picker.utils.MediaUtils
import com.doris.media.picker.utils.permission.MyPermissionsUtils
import com.hjq.permissions.Permission
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.lxj.xpopup.XPopup
import com.lxj.xpopupext.listener.CommonPickerListener
import com.lxj.xpopupext.listener.TimePickerListener
import com.lxj.xpopupext.popup.CommonPickerPopup
import com.lxj.xpopupext.popup.TimePickerPopup
import com.rxjava.rxlife.RxLife
import com.hand.wfive.App
import com.hand.wfive.BuildConfig
import com.hand.wfive.R
import com.hand.wfive.activity.sign.SignActivity
import com.hand.wfive.ad.AdFragment
import com.hand.wfive.adapter.FileAdapter
import com.hand.wfive.base.BaseActivity
import com.hand.wfive.base.Constant
import com.hand.wfive.entity.*
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.loginAndVip.ui.H5PayActivity
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.FuncSwitchUtils
import com.hand.wfive.util.GsonUtil
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.util.oss.OssRequest
import com.hand.wfive.view.InputDialog
import com.hand.wfive.view.MsgDialog2
import com.hand.wfive.view.dialog.MoreActionView
import com.hand.wfive.view.dialog.MoreFileCenter
import com.hand.wfive.view.dialog.WordDownNoticeView
import com.lxj.xpopup.core.BasePopupView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_file_item.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.find
import org.jetbrains.anko.support.v4.toast
import org.jetbrains.anko.textColor
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.asClass
import java.io.File
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.concurrent.TimeUnit
import kotlin.math.abs


abstract class BaseFileFragment : AdFragment() {

    private var mPage = 1
    var select_type: String? = null
    var select_format: Int? = null
    var select_date: Date? = null

    protected lateinit var mAdapter: FileAdapter
    private lateinit var mTurnH5Pay: ActivityResultLauncher<Intent>
    var mOrderDataModel: WordDownOrderModel? = null

    var mode = 1
    override fun getLayoutId() = R.layout.fragment_file_item

    override fun init() {
        registerEventBus()
        mTurnH5Pay = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == BaseActivity.RESULT_OK) {
                getOrderStatus()
            }
        }
    }


    override fun initKotlinWidget() {
        mAdapter = FileAdapter()
        mAdapter.addChildClickViewIds(R.id.iv_more)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (mode) {
                1 -> {
                    showMore(position)
                }

                2 -> {
                    showMode2(position,view)
                }
            }

        }
        mAdapter.setOnItemClickListener { _, _, position ->
            val model = mAdapter.getItem(position)
            sign(model)
        }
        recycler_file.layoutManager = LinearLayoutManager(mContext)
        (recycler_file.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        recycler_file.adapter = mAdapter
        mAdapter.setEmptyView(getEmptyView())

        mAdapter.loadMoreModule.isEnableLoadMore = true
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            loadData()
        }

        loadData()
    }

    private fun getEmptyView(): View {
        val view = LayoutInflater.from(mContext)
            .inflate(R.layout.item_file_empty, recycler_file, false)
        view.find<TextView>(R.id.tv_tip).text = emptyMsg()
        return view
    }

    @OnClick(R.id.ll_select_date, R.id.ll_file_type_select, R.id.ll_file_format_select)
    fun onClick(view: View) {
        when (view.id) {
            R.id.ll_select_date -> {
                val date: Calendar = Calendar.getInstance()
                date.set(1990, 5, 1)
                val date2: Calendar = Calendar.getInstance()
                date2.set(2080, 5, 1)
                var defaultDate = Calendar.getInstance()
                if (select_date != null)
                    defaultDate.time = select_date
                else
                    defaultDate.time = Date()
                val popup =
                    TimePickerPopup(mContext)
                        .setDefaultDate(defaultDate)  //设置默认选中日期
                        .setYearRange(1990, 2080) //设置年份范围
                        .setDateRange(date, date2) //设置日期范围
                        .setTimePickerListener(object : TimePickerListener {
                            override fun onTimeChanged(date: Date) {
                            }

                            override fun onTimeConfirm(date: Date, view: View) {
                                select_date = date
                                val formatter = SimpleDateFormat("yyyy-MM-dd")
                                var dateString = formatter.format(date)
                                tv_date.text = dateString
                                tv_date.textColor = Color.parseColor("#1989FD")
                                mPage = 1
                                loadData()
                            }

                            override fun onCancel() {
                                select_date = null
                                tv_date.text = "日期筛选"
                                tv_date.textColor = Color.parseColor("#FF171717")
                                mPage = 1
                                loadData()
                            }
                        })

                XPopup.Builder(mContext)
                    .asCustom(popup)
                    .show()
            }

            R.id.ll_file_format_select,
            R.id.ll_file_type_select -> {
                val popup = CommonPickerPopup(mContext)
                val list = ArrayList<String>()
                list.add("全部")
                list.add("图片")
                list.add("文档")
                list.add("pdf")
                var currentItemIndex = 0
                var type = ""
                type = if (select_type == null) {
                    getType()
                } else {
                    select_type as String
                }
                if (type == Params.fileTypeAll) {
                    currentItemIndex = 0
                }
                if (type == Params.fileTypeImage) {
                    currentItemIndex = 1
                }
                if (type == Params.fileTypeWord) {
                    currentItemIndex = 2
                }
                if (type == Params.fileTypePdf) {
                    currentItemIndex = 3
                }
                popup.setPickerData(list)
                    .setCurrentItem(currentItemIndex)
                popup.setCommonPickerListener(object : CommonPickerListener {
                    override fun onItemSelected(index: Int, data: String?) {
                        when (index) {
                            0 -> {
                                select_type = Params.fileTypeAll
                                tv_file_format.text = "文件格式"
                                tv_file_type.text = "文件类型"
                                tv_file_type.textColor = Color.parseColor("#FF171717")
                                tv_file_format.textColor = Color.parseColor("#FF171717")
                            }

                            1 -> {
                                select_type = Params.fileTypeImage
                                tv_file_format.text = "图片"
                                tv_file_type.text = "图片"
                                tv_file_type.textColor = Color.parseColor("#1989FD")
                                tv_file_format.textColor = Color.parseColor("#1989FD")
                            }

                            2 -> {
                                select_type = Params.fileTypeWord
                                tv_file_format.text = "文档"
                                tv_file_type.text = "文档"
                                tv_file_type.textColor = Color.parseColor("#1989FD")
                                tv_file_format.textColor = Color.parseColor("#1989FD")
                            }

                            3 -> {
                                select_type = Params.fileTypePdf
                                tv_file_format.text = "pdf"
                                tv_file_type.text = "pdf"
                                tv_file_type.textColor = Color.parseColor("#1989FD")
                                tv_file_format.textColor = Color.parseColor("#1989FD")
                            }
                        }
                        mPage = 1
                        loadData()
                    }

                    override fun onCancel() {

                    }
                })
                XPopup.Builder(mContext)
                    .asCustom(popup)
                    .show()
            }
        }
    }

    protected abstract fun getType(): String

    protected abstract fun emptyMsg(): String

    open fun getStatus() = ""

    private fun loadData() {
        var load_file_type = getType()
        if (select_type != null) {
            load_file_type = select_type as String
        }
        val formatter = SimpleDateFormat("yyyy-MM-dd")
        var dateString = ""
        if (select_date != null) {
            dateString = formatter.format(select_date)
        }

        RxHttp.postForm(ApiConfig.getUserFileList)
            .add("appid", LoginConfig.AppId)
            .add("userId", UserManager.getInstance().userId)
            .add("status", getStatus())
            .add("type", load_file_type)
            .add("cloudFileType", select_format)
            .add("time", dateString)
            .add("pageSize", 20)
            .add("page", mPage)
            .asClass<FileListModel>()
            .to(RxLife.toMain(this))
            .subscribe({
                Log.e("loadData", it.toString())
                if (it.code == ApiConfig.SUCCESSCODE) {
                    if (mPage == 1) {
                        mAdapter.setNewInstance(it.data.records)
                    } else {
                        mAdapter.addData(it.data.records)
                    }
                    if (it.data.records.isEmpty()) {
                        mAdapter.loadMoreModule.loadMoreEnd()
                    } else {
                        mPage++
                        mAdapter.loadMoreModule.loadMoreComplete()
                    }
                } else resetPage()
            }, {
                resetPage()
            })
    }

    private fun resetPage() {
        mPage--
        if (mPage < 1) mPage = 1
        mAdapter.loadMoreModule.loadMoreComplete()
    }

    @SuppressLint("CheckResult")
    private fun sign(model: FileModel) {
        if (model.type == Params.fileTypePdf) {
            pdfSign(model)
//        } else if (model.type == Params.fileTypeWord && model.coverFileId.isEmpty()) {
        } else if (model.type == Params.fileTypeWord) {
            RxHttp.postForm(ApiConfig.getWordImageData)
                .add("userId", UserManager.getInstance().userId)
                .add("cloudFileId", model.id)
                .add("appid", LoginConfig.AppId)
                .asClass(WordImagesModel::class.java)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
                    if (it.code == 200) {
                        SignActivity.show(mContext, model)
                    } else if (it.code == 203) {
                        showNormalTip("此文档正在上传，请稍后")
                    } else {
                        showNormalTip("此文档暂不可签名")
                    }

                }

        } else {
            SignActivity.show(mContext, model)
        }
    }

    private fun pdfSign(model: FileModel) {
        val suffix = model.fileId.substring(model.fileId.lastIndexOf("."))
        model.filePath = if (model.fileName.endsWith(suffix, true)) {
            "${App.getContext().cacheSignPath}/${model.fileName}"
        } else {
            "${App.getContext().cacheSignPath}/${model.fileName}${suffix}"
        }
        val file = File(model.filePath)
        if (file.exists() && FileUtils.getFileSize(file) == model.size) {
            SignActivity.show(mContext, model)
        } else {
            showLoadingTipC()
            OssRequest.getInstance().dowloadFile(
                model.fileId, model.filePath, object : OssCallBack {
                    override fun onSuccess() {
                        dismissTip()
                        SignActivity.show(mContext, model)
                    }

                    override fun onFailure(msg: String) {
                        showNormalTip(if (msg.contains("下载")) "打开失败" else msg)
                    }
                })
        }
    }

    private fun to_share_file(model: FileModel) {
        val uris = ArrayList<Uri>()
        for (path in shareUris) {
            val file = File(path)
            val u = FileProvider.getUriForFile(
                mContext,
                "${BuildConfig.APPLICATION_ID}.fileprovider",
                file
            )
            uris.add(u)
        }
        shareUris.clear()
        val multiple: Boolean = uris.size > 1
        val intent = Intent(if (multiple) Intent.ACTION_SEND_MULTIPLE else Intent.ACTION_SEND)
        when (model.type) {
            Params.pickerImage -> {
                intent.type = "image/*"
            }

            else -> {
                intent.type = "*/*"
            }
        }


        if (multiple) {

            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
        } else {

            intent.putExtra(Intent.EXTRA_STREAM, uris[0])
        }
        startActivity(Intent.createChooser(intent, "分享到"));
    }
    var moreDialogview:BasePopupView?=null
    @SuppressLint("CheckResult")
    fun showMoreDialog(model: FileModel, position: Int) {
        if (moreDialogview!=null){
            if (moreDialogview!!.isShow){
                moreDialogview!!.dismiss()
            }
            moreDialogview=null
        }
         moreDialogview = XPopup.Builder(this.mContext)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(true)
            .asCustom(MoreActionView(
                this.mContext, model
            ) {
                when (it) {
                    1 -> {
                        //发起签字
                        sign(model)
                    }

                    2 -> {
                        //存云空间
                        showNormalTip("暂未开放此功能")
                    }

                    3 -> {
                        //保存手机
                        shareUris.clear()
                        if (FuncSwitchUtils.canUse(FuncSwitchUtils.FuncSave)) {
                            export(model, false)
                        } else {
                            showVip()
                        }
                    }

                    4 -> {
                        //分享
                        if (FuncSwitchUtils.canUse(FuncSwitchUtils.FuncSave)) {
                            export(model, true)
                        } else {
                            showVip()
                        }

                    }

                    5 -> {
                        showLoadingTipC()
                        RxHttp.postForm(ApiConfig.getWordImageData)
                            .add("userId", UserManager.getInstance().userId)
                            .add("cloudFileId", model.id)
                            .add("appid", LoginConfig.AppId)
                            .asClass(WordImagesModel::class.java)
                            .flatMap { wordImagesModel ->
                                if (TextUtils.isEmpty(wordImagesModel.`object`.wordTime)) {
                                    RxHttp.postForm(ApiConfig.getAppServerConfig)
                                        //                                    .add("appKey", getString(R.string.CodeAppKey))
                                        .add("appKey", LoginConfig.AppId)
                                        .add("serverType", "3")
                                        .asClass(WordDownOrderModel::class.java)
                                        .map { mOrderDataModel ->
                                            mOrderDataModel.images =
                                                wordImagesModel.`object`.imageVoList
                                            mOrderDataModel.imageSize =
                                                wordImagesModel.`object`.imageVoList.size.toString()
                                            mOrderDataModel.fileId = wordImagesModel.`object`.fileId
                                            mOrderDataModel.fileName = model.fileName
                                            mOrderDataModel
                                        }
                                } else {
                                    val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                    var wordtime = wordImagesModel.`object`.wordTime
                                    var date1 = sdf.parse(wordtime)
                                    val date2 = Date(System.currentTimeMillis())
                                    val diffInDays: Long =
                                        abs((date2.time - date1.time) / (24 * 60 * 60 * 1000))
                                    if (diffInDays > 7) {
                                        RxHttp.postForm(ApiConfig.getAppServerConfig)
                                            //                                    .add("appKey", getString(R.string.CodeAppKey))
                                            .add("appKey", LoginConfig.AppId)
                                            .add("serverType", "3")
                                            .asClass(WordDownOrderModel::class.java)
                                            .map { mOrderDataModel ->
                                                mOrderDataModel.images =
                                                    wordImagesModel.`object`.imageVoList
                                                mOrderDataModel.imageSize =
                                                    wordImagesModel.`object`.imageVoList.size.toString()
                                                mOrderDataModel.fileId =
                                                    wordImagesModel.`object`.fileId
                                                mOrderDataModel.fileName = model.fileName
                                                mOrderDataModel
                                            }
                                    } else {
                                        var mOrderDataModel = WordDownOrderModel()
                                        mOrderDataModel.wordUrl =
                                            wordImagesModel.`object`.wordFileUrl.toString()
                                        mOrderDataModel.fileId =
                                            wordImagesModel.`object`.fileId
                                        mOrderDataModel.fileName = model.fileName
                                        Observable.create<WordDownOrderModel> { emit ->
                                            emit.onNext(mOrderDataModel)
                                            emit.onComplete()
                                        }

                                    }

                                }

                            }
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe({ mOrderDataModel ->
                                dismissTip()
                                if (!TextUtils.isEmpty(mOrderDataModel.wordUrl)) {
                                    //直接下载
                                    showDownLoadingProgress()
                                    downWord(
                                        mOrderDataModel.wordUrl!!,
                                        mOrderDataModel.fileName!!
                                    )
                                } else {
                                    if (mOrderDataModel.code == 200) {
                                        XPopup.Builder(mContext)
                                            .dismissOnBackPressed(false)
                                            .dismissOnTouchOutside(true)
                                            .asCustom(WordDownNoticeView(
                                                mContext, mOrderDataModel
                                            ) { payPrice, payType ->

                                                h5Pay(payPrice, payType, mOrderDataModel)
                                            }).show()

                                    } else {
                                        dismissTip()
                                        showNormalTip("获取数据失败")
                                    }
                                }
                            }, {
                                dismissTip()
                                showNormalTip("获取数据失败")
                            })


                    }

                    6 -> {
                        //文件重命名
                        rename(model, position)
                    }

                    7 -> {
                        //删除
                        delete(model)
                    }
                }
            })
        moreDialogview!!.show()
    }

    private fun showMode2(position: Int,view: View) {
        val model = mAdapter.getItem(position)
        if (model.type == Params.fileTypeWord) {
            RxHttp.postForm(ApiConfig.getWordImageData)
                .add("userId", UserManager.getInstance().userId)
                .add("cloudFileId", model.id)
                .add("appid", LoginConfig.AppId)
                .asClass(WordImagesModel::class.java)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
                    if (it.code == 200) {
                        mode2dialog(model,view)
                    } else if (it.code == 203) {
                        showNormalTip("此文档正在上传，请稍后")
                    } else {
                        showNormalTip("加载失败")
                    }

                }
        } else {
            mode2dialog(model,view)
        }


    }

    private fun mode2dialog(model: FileModel,view: View) {
        XPopup.Builder(mContext)
            .dismissOnBackPressed(false).hasShadowBg(false)
            .atView(view)
            .asCustom(MoreFileCenter(mContext).addOnMoreFileCenterCallBack {
                when (it) {
                    1 -> {
                        //签字
                        sign(model)
                    }

                    2 -> {
                        //预览
                        ARouter.getInstance()
                            .build(Constant.Path.PreviewActivity)
                            .withParcelable("model", model)
                            .navigation()
                    }

                    3 -> {
                        //保存手机
                        if (FuncSwitchUtils.canUse(FuncSwitchUtils.FuncSave)) {
                            export(model, false)
                        } else {
                            showVip()
                        }
                    }

                    4 -> {
                        delete(model)
                    }
                }

            }).show()
    }

    @SuppressLint("CheckResult")
    private fun showMore(position: Int) {
        val model = mAdapter.getItem(position)
        if (model.type == Params.fileTypeWord) {
            RxHttp.postForm(ApiConfig.getWordImageData)
                .add("userId", UserManager.getInstance().userId)
                .add("cloudFileId", model.id)
                .add("appid", LoginConfig.AppId)
                .asClass(WordImagesModel::class.java)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
                    if (it.code == 200) {
                        showMoreDialog(model, position)
                    } else if (it.code == 203) {
                        showNormalTip("此文档正在上传，请稍后")
                    } else {
                        showNormalTip("加载失败")
                    }

                }
        } else {
            showMoreDialog(model, position)
        }


//        val model = mAdapter.getItem(position)
//        val dialog = Dialog(mContext, R.style.CustomDialog)
//        dialog.setContentView(R.layout.dialog_file_more)
//        dialog.find<TextView>(R.id.tv_title).text = model.fileName
//        dialog.find<ImageView>(R.id.iv_sign).singleClick {
//            dialog.dismiss()
//            sign(model)
//        }
//        dialog.find<ImageView>(R.id.iv_export).singleClick {
//            dialog.dismiss()
//            if (FuncSwitchUtils.canUse(FuncSwitchUtils.FuncSave)){
//                export(model)
//            }else{
//                showVip()
//            }
//        }
//        dialog.find<ImageView>(R.id.iv_rename).singleClick {
//            dialog.dismiss()
//            rename(model, position)
//        }
//        dialog.find<ImageView>(R.id.iv_delete).singleClick {
//            dialog.dismiss()
//            delete(model)
//        }
//        // 底部显示
//        dialog.bottomShow()
    }


    private fun h5Pay(payPrice: String, payType: String, mOrderDataModel: WordDownOrderModel) {
        this.mOrderDataModel = mOrderDataModel
        mOrderDataModel.payType = payType

        val randomInt = ((Math.random() * 9 + 1) * 1000).toInt()
        mOrderDataModel.orderNo =
            "${System.currentTimeMillis()}_${randomInt}_${getString(R.string.channel)}"
        mOrderDataModel.remark =
            "${mOrderDataModel.data?.serverName}-${getString(R.string.app_name)}"
        val user = UserManager.getInstance().curUser
        val orderUrl = "${ApiConfig.basePayUrl}orderApi/serverOrderView?" +
                "code=${mOrderDataModel.orderNo}&amount=${payPrice}&name=${mOrderDataModel.remark}" +
                "&remark=${mOrderDataModel.remark}&appid=${LoginConfig.AppId}" +
                "&username=${user.username}&userid=${user.id}" +
                "&type=${payType}"
        mTurnH5Pay.launch(H5PayActivity.showIntent(mContext, orderUrl, payType))

    }

    var taskObservable: Disposable? = null
    var taskCount = 0

    @SuppressLint("CheckResult")
    protected fun getOrderStatus() {

        showLoadingTipC("正在查询支付状态")
        val orderOb = RxHttp.postForm(ApiConfig.getOrderStatus)
            .add("orderNo", mOrderDataModel!!.orderNo)
            .add("appId", LoginConfig.AppId)
            .add("userId", UserManager.getInstance().userId)
            .asClass(OrderStatusModel::class.java)
        taskObservable = Observable.interval(4, TimeUnit.SECONDS)
            .flatMap {
                orderOb
            }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
                if (it.code == 200) {
                    taskCount++
                    // 支付状态 0-未支付 1-支付中 2-支付成功 3-支付失败 4-已取消
                    when (it.data) {
                        3, 4 -> {
                            if (!taskObservable!!.isDisposed) {
                                taskObservable!!.dispose()
                                taskCount = 0
                                dismissTip()
                            }

                            showNormalTip("支付失败")
                        }

                        0, 1 -> {

                            if (taskCount > 3) {
                                if (!taskObservable!!.isDisposed) {
                                    taskObservable!!.dispose()
                                    dismissTip()
                                    taskCount = 0
                                    showNormalTip("支付失败，请联系客服")
                                }

                            }
                        }

                        2 -> {

                            if (!taskObservable!!.isDisposed) {
                                taskObservable!!.dispose()
                                taskCount = 0
                            }
                            dismissTip()
                            //开始转word下载
                            showDownLoadingProgress()
                            prepareDownWord()
                        }
                    }

                }
            }, {
                showNormalTip("获取订单失败，请联系客服")

            })
    }


    private fun prepareDownWord() {

        val images = mOrderDataModel!!.images
        RxHttp.postForm(ApiConfig.imagesToWordFile)
            .add("userId", UserManager.getInstance().userId)
            .add("images", GsonUtil.gsonString(images))
            .add("appid", LoginConfig.AppId)
            .asClass(FileWord2ImagesModel::class.java)
            .to(RxLife.toMain(this))
            .subscribe({
                if (it.code == 200) {
                    //开始下一步
                    mOrderDataModel!!.fileId?.let { it1 ->
                        createWordFinish(
                            it.data,
                            GsonUtil.gsonString(images),
                            fileId = it1
                        )
                    }
                } else {
                    showNormalTip("下载失败，请联系客服")
                }
            }, {
                showNormalTip("下载失败，请联系客服")

            })

    }

    private fun createWordFinish(taskId: String, images: String, fileId: String) {
        val taskOb = RxHttp.postForm(ApiConfig.imagesToWordIsDone)
            .add("userId", UserManager.getInstance().userId)
            .add("images", images)
            .add("fileId", fileId)
            .add("appid", LoginConfig.AppId)
            .add("taskId", taskId)
            .asClass(FileWord2ImagesModel::class.java)
        taskObservable = Observable.interval(3, TimeUnit.SECONDS)
            .flatMap {
                taskOb
            }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
                taskCount++
                if (it.code == 200) {
                    //开始下载
                    if (!taskObservable!!.isDisposed) {
                        taskObservable!!.dispose()
                        taskCount = 0
                    }
                    downWord(it.data, mOrderDataModel!!.fileName!!)

                } else {
                    if (taskCount > 3) {
                        taskCount = 0
                        if (!taskObservable!!.isDisposed) {
                            taskObservable!!.dispose()
                            taskCount = 0
                        }
                        showNormalTip("转换失败，请联系客服")
                    }
                }

            }, {
                showNormalTip("转换失败，请联系客服")
            })
    }

    private fun downWord(url: String, fileName: String) {
        val suffix = url.substring(url.lastIndexOf("."))
        var regexPattern = "\\.[^\\.]*$".toRegex()
        val currentTimeMillis = System.currentTimeMillis()
        var fileName = currentTimeMillis.toString() + fileName
        var path = App.getContext().downloadPath + "/" + fileName.replace(
            regexPattern,
            suffix
        )
        FileDownloader.getImpl().create(url)
            .setPath(path)
            .setListener(object : FileDownloadListener() {
                override fun pending(
                    task: BaseDownloadTask,
                    soFarBytes: Int,
                    totalBytes: Int
                ) {

                }

                override fun progress(
                    task: BaseDownloadTask,
                    soFarBytes: Int,
                    totalBytes: Int
                ) {

                }

                override fun completed(task: BaseDownloadTask) {
                    dismissTip()
                    MediaUtils.refreshSystemMedia(mContext, task.path)
                    showSuccessTip("文件已导出保存至下载目录")
//                    showNormalTip("下载成功${task.path}")
                }

                override fun paused(
                    task: BaseDownloadTask,
                    soFarBytes: Int,
                    totalBytes: Int
                ) {

                }

                override fun error(task: BaseDownloadTask, e: Throwable?) {
                    dismissTip()
                    showNormalTip("下载失败")

                }

                override fun warn(task: BaseDownloadTask) {

                }
            }).start()

    }


    private var mExportIndex = 0
    private var mExportErrorCount = 0
    private var mExportSuccessCount = 0
    private val mExportFileIds = ArrayList<String>()
    private lateinit var mExportFileName: String

    private fun export(model: FileModel, isShare: Boolean) {
        MyPermissionsUtils.requestPermissionsTurn(
            this, "用于导出文件至手机",
            object : MyPermissionsUtils.HavePermissionListener {
                override fun havePermission() {
                    showLoadingTipC()
                    mExportIndex = 0
                    mExportErrorCount = 0
                    mExportSuccessCount = 0

                    mExportFileIds.clear()
                    if (model.fileId.contains(",")) {
                        mExportFileIds.addAll(model.fileId.split(","))
                    } else {
                        mExportFileIds.add(model.fileId)
                    }
                    if (model.coverFileId.isNotEmpty() && !isShare) {
                        mExportFileIds.add(model.coverFileId)
                    }
                    mExportFileName = model.fileName
                    downloadFile(model, isShare)
                }
            }, Permission.WRITE_EXTERNAL_STORAGE
        )
    }

    var shareUris = ArrayList<String>()

    @SuppressLint("CheckResult")
    private fun downloadFile(model: FileModel, isShare: Boolean) {
        val suffix = mExportFileIds[mExportIndex]
            .substring(mExportFileIds[mExportIndex].lastIndexOf("."))
        val savePath = if (mExportFileIds.size == 1) {
            if (mExportFileName.endsWith(suffix, true)) {
                "${App.getContext().downloadPath}/${mExportFileName}"
            } else {
                "${App.getContext().downloadPath}/${mExportFileName}${suffix}"
            }
        } else {
            if (mExportFileName.endsWith(suffix, true)) {
                "${App.getContext().downloadPath}/(${mExportIndex + 1})${mExportFileName}"
            } else {
                "${App.getContext().downloadPath}/${mExportFileName}(${mExportIndex + 1})${suffix}"
            }
        }
        if (isShare) {
            shareUris.add(savePath)
        }
//        if (isShare && model.type == Params.fileTypeWord && model.status == Params.fileStatusSign) {
        if (model.type == Params.fileTypeWord) {

            //下载签名后的
            RxHttp.postForm(ApiConfig.getWordImageData)
                .add("userId", UserManager.getInstance().userId)
                .add("cloudFileId", model.id)
                .add("appid", LoginConfig.AppId)
                .asClass(WordImagesModel::class.java)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.code == 200) {
                        shareUris.clear()
                        var regexPattern = "\\.[^\\.]*$".toRegex()
                        var path = if (mExportFileName.endsWith(suffix, true)) {
                            App.getContext().downloadPath + "/" + mExportFileName.replace(
                                regexPattern,
                                ".pdf"
                            )
                        } else {
                            App.getContext().downloadPath + "/" + mExportFileName + ".pdf"
                        }

                        shareUris.add(path)

                        FileDownloader.getImpl().create(it.`object`.pdfFileUrl.toString())
                            .setPath(path)
                            .setListener(object : FileDownloadListener() {
                                override fun pending(
                                    task: BaseDownloadTask,
                                    soFarBytes: Int,
                                    totalBytes: Int
                                ) {

                                }

                                override fun progress(
                                    task: BaseDownloadTask,
                                    soFarBytes: Int,
                                    totalBytes: Int
                                ) {

                                }

                                override fun completed(task: BaseDownloadTask) {
                                    dismissTip()
                                    MediaUtils.refreshSystemMedia(mContext, task.path)
                                    if (isShare)
                                        to_share_file(model)
                                    else
                                        showSuccessTip("文件已导出保存至下载目录")
                                }

                                override fun paused(
                                    task: BaseDownloadTask,
                                    soFarBytes: Int,
                                    totalBytes: Int
                                ) {

                                }

                                override fun error(task: BaseDownloadTask, e: Throwable?) {
                                    dismissTip()
                                    if (isShare)
                                        showNormalTip("数据异常")
                                }

                                override fun warn(task: BaseDownloadTask) {

                                }
                            }).start()
                    } else {
                        showNormalTip("数据异常")

                    }
                }, {
                    showNormalTip("数据异常")

                })

        } else {
            OssRequest.getInstance().dowloadFile(
                mExportFileIds[mExportIndex], savePath, object : OssCallBack {
                    override fun onSuccess() {
                        MediaUtils.refreshSystemMedia(mContext, savePath)
                        mExportIndex++
                        mExportSuccessCount++
                        if (mExportFileIds.size > mExportIndex) downloadFile(model, isShare)
                        else dowloadOver(model, isShare)
                    }

                    override fun onFailure(msg: String) {
                        mExportIndex++
                        mExportErrorCount++
                        if (mExportFileIds.size > mExportIndex) downloadFile(model, isShare)
                        else dowloadOver(model, isShare)
                    }
                })
        }

    }

    private fun dowloadOver(model: FileModel, isShare: Boolean) {
        if (mExportSuccessCount == mExportFileIds.size) {
            if (isShare) {
                //分享
                dismissTip()
                to_share_file(model)
            } else {
                showSuccessTip("文件已导出保存至下载目录")
            }
        } else {
            showSuccessTip("文件已导出保存至下载目录\n${mExportSuccessCount}个导出成功，${mExportErrorCount}个导出失败")
        }
        FuncSwitchUtils.addUseCount(FuncSwitchUtils.FuncSave)
    }

    private fun rename(model: FileModel, position: Int) {
        InputDialog(mContext, "重命名", model.fileName, content = model.fileName) { dialog, value ->
            if (value.isEmpty()) {
                toast("请输入文件名！")
                return@InputDialog
            }
            if (value == model.fileName) {
                dialog.dismiss()
                return@InputDialog
            }
            dialog.dismiss()
            showLoadingTipC()
            OssRequest.getInstance().renameFile(model, value, object : OssCallBack {
                override fun onSuccess() {
                    dismissTip()
                    model.fileName = value
                    mAdapter.notifyItemChanged(position)
                    onUpdateFile(FileUpdateEvent(2, model))
                }

                override fun onFailure(msg: String) {
                    showNormalTip(msg)
                }
            })
        }.show()
    }

    private fun delete(model: FileModel) {
        MsgDialog2(
            mContext, "删除提醒", "您确定删除此签名文件吗？\n删除后将无法找回",
            negativeBg = R.drawable.btn_dialog_msg_positive_red_left,
            positiveBg = R.drawable.btn_dialog_msg_negative_right,
            negativeText = "确定",
            positiveText = "取消",
        ) {
            if (it == 0) {
                showLoadingTipC()
                OssRequest.getInstance().delCloudFile(model, object : OssCallBack {
                    override fun onSuccess() {
                        dismissTip()
                        mAdapter.remove(model)
                        onUpdateFile(FileUpdateEvent(1, model))
                    }

                    override fun onFailure(msg: String) {
                        showNormalTip(msg)
                    }
                })
            }
        }.show()
    }

    protected abstract fun onUpdateFile(event: FileUpdateEvent)

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun doFileEvent(event: FileEvent) {
        if (event.type == getType() &&
            (getStatus().isEmpty() || event.status.isEmpty() || event.status == getStatus())
        ) {
            mPage = 1
            loadData()
        }
    }
}